<template>
  <div class="article-page">
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item>面经后台</el-breadcrumb-item>
      <el-breadcrumb-item>面经管理</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card shadow="never" border="false">
      <template #header>
        <div class="header">
          <span>共 {{ total }} 条记录</span>
          <el-button
            icon="el-icon-plus"
            size="small"
            type="primary"
            round
            @click="openDrawer('add')"
          >
            添加面经
          </el-button>
        </div>
      </template>
      <!-- :data 让el-table给你渲染数据 -->
      <!-- el-table-column:配置prop 渲染指定的子弹-->
      <el-table :data="list">
        <el-table-column label="标题" prop="stem"></el-table-column>
        <el-table-column label="作者" prop="creator"></el-table-column>
        <el-table-column label="点赞" prop="likeCount"></el-table-column>
        <el-table-column label="浏览数" prop="views"></el-table-column>
        <el-table-column label="创建时间" prop="createdAt"></el-table-column>
        <el-table-column label="操作">
          <!-- 通过作用域插槽 获取每一行的数据 -->
          <template #default="{ row }">
            <div class="actions">
              <i
                class="el-icon-view"
                @click="openDrawer('preview', row.id)"
              ></i>
              <i
                class="el-icon-edit-outline"
                @click="openDrawer('edit', row.id)"
              ></i>
              <i class="el-icon-delete" @click="del(row.id)"></i>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <!-- el-table内部 只能放el-table-column,所以分页应该是放在 el-table外部 -->
      <!-- layout：展示咱们分页的样式 -->
      <!-- size-change：页容量变化的时候 触发的事件 -->
      <!-- current-change：页码变化的时候 触发的事件 -->
      <!-- current-page: 当前页码 -->
      <!-- page-sizes：页容量的下拉 -->
      <!-- page-size:页容量 -->
      <el-pagination
        background
        @current-change="handleCurrentChange"
        :current-page="current"
        :page-size="pageSize"
        layout="prev, pager, next"
        :total="total"
      >
      </el-pagination>
    </el-card>
    <!-- title:表示标题 -->
    <!-- visible：表示抽屉的显示和隐藏 .sync 在子组件内部 去修改visible -->
    <!-- direction: 表示抽屉的打开方向 rtl -->
    <!-- before-close:关闭之前的一个询问 -->
    <el-drawer
      :title="drawerTitle"
      :visible.sync="drawer"
      :direction="direction"
      size="60%"
      @close="handleClose"
    >
      <!-- el-form:  :model :rules -->
      <!-- el-form-item  prop -->
      <!-- el-input:  v-model -->
      <div v-if="drawerType === 'preview'" class="article-preview">
        <h5>{{ form.stem }}</h5>
        <div v-html="form.content"></div>
      </div>
      <el-form
        v-else
        ref="form"
        label-width="80px"
        :model="form"
        :rules="rules"
      >
        <el-form-item label="标题" prop="stem">
          <el-input placeholder="输入面经标题" v-model="form.stem"></el-input>
        </el-form-item>
        <el-form-item label="内容" prop="content">
          <!-- el-form的表单校验 默认只对 element 内置的表单元素进行校验 -->
          <!-- quillEditor 不是element-ui提供的所以只能自己校验 -->
          <quillEditor
            v-model="form.content"
            @blur="$refs.form.validateField('content')"
          ></quillEditor>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSubmit">确认</el-button>
          <el-button @click="handleClose">取消</el-button>
        </el-form-item>
      </el-form>
    </el-drawer>
  </div>
</template>

<script>
import {
  getArticleListApi,
  createArticleApi,
  delArticleApi,
  getArticleDetailApi,
  editArticleApi
} from '@/api/article'
// require styles
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'
import { quillEditor } from 'vue-quill-editor'
export default {
  name: 'article-page',
  data () {
    return {
      // 当前页
      current: 1,
      // 当前页容量
      pageSize: 10,
      // 每页的数据
      list: [],
      total: 0,
      // 抽屉默认关闭,
      drawer: false,
      // 打开方向 右->左
      direction: 'rtl',
      // 记录哪个按钮点击的
      drawerType: '',
      form: {
        // 题目
        stem: '',
        // 内容
        content: ''
      },
      rules: {
        stem: [{ required: true, message: '标题不可为空', trigger: 'blur' }],
        content: [{ required: true, message: '内容不可为空', trigger: 'blur' }]
      }
    }
  },
  components: {
    quillEditor
  },
  created () {
    // 首次进入 获取数据
    this.getList()
  },
  computed: {
    drawerTitle () {
      let title = ''
      if (this.drawerType === 'add') {
        title = '添加面经'
      }
      if (this.drawerType === 'preview') {
        title = '面经预览'
      }
      if (this.drawerType === 'edit') {
        title = '修改面经'
      }
      return title
    }
  },
  methods: {
    handleSubmit () {
      this.$refs.form.validate(async (flag) => {
        // console.log(flag)
        if (!flag) return
        if (this.drawerType === 'add') {
          await createArticleApi(this.form)
          this.$message.success('添加成功')
        }
        if (this.drawerType === 'edit') {
          const { id, stem, content } = this.form
          await editArticleApi({ id, stem, content })
          this.$message.success('编辑成功')
        }
        this.current = 1
        this.getList()
        this.handleClose()
      })
    },
    // 清空表单的内容
    handleClose () {
      this.drawer = false
      // 重置表单数据
      if (this.drawerType !== 'preview') {
        // 只有添加和修改的时候 重置表单数据
        this.$refs.form.resetFields()
      }
      // 重置form中的数据（原因：修改时回显的时候 返回的字段多了）
      this.form = {
        stem: '',
        content: ''
      }
    },
    // type 来判断是谁点击的
    // id 点击编辑或者预览时 获取当前行点击的id
    async openDrawer (type, id) {
      this.drawer = true
      this.drawerType = type
      // 只要不是添加都要回显
      if (type !== 'add') {
        // 编辑功能
        const res = await getArticleDetailApi(id)
        this.form = res.data
      }
    },
    /**
     * 删除功能
     */
    del (id) {
      // console.log(id)
      this.$confirm('确定要删除此数据吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          // 说明用户点击了确定
          await delArticleApi(id)
          this.$message.success('删除成功')
          // 判断 当前删除的是不是最后一条(对最后一页的处理)
          if (this.list.length === 1 && this.current > 1) {
            this.current--
          }
          this.getList()
        })
        .catch(() => {
          // 说明点击了取消，并且catch必须要配置
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    async getList () {
      const res = await getArticleListApi({
        current: this.current,
        pageSize: this.pageSize
      })
      this.list = res.data.rows
      this.total = res.data.total
    },
    handleCurrentChange (val) {
      this.current = val
      // 重新获取当前这一页的数据
      this.getList()
    }
  }
}
</script>

<style lang="scss" scoped>
.el-card {
  margin-top: 25px;
  .header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding-right: 16px;
  }
  .actions {
    font-size: 18px;
    display: flex;
    justify-content: space-around;
    color: #666;
    > i:hover {
      color: rgba(114, 124, 245, 1);
      cursor: pointer;
    }
  }
}
.el-pagination {
  margin-top: 20px;
  text-align: center;
}
.el-breadcrumb {
  margin-top: 10px;
}
.el-form {
  padding-right: 40px;
}
.quill-editor {
  ::v-deep .ql-editor {
    height: 300px;
  }
}
.el-rate {
  padding: 10px 0;
}
.article-preview {
  padding: 0 40px 40px 40px;
  > h5 {
    font-size: 20px;
    color: #666;
    border-bottom: 1px dashed #ccc;
    padding-bottom: 30px;
    margin: 0 0 20px 0;
  }
}
</style>
